<?php

namespace App\Models\Logger;

use App\Models\Concerns\ScopeFilterable;
use Illuminate\Database\Eloquent\Model;

/**
 * @property string remark
 * @property string type
 * @property int id
 */
class LogType extends Model
{
    use ScopeFilterable;

    protected $table = 'log_types';

    protected static $unguarded = true;

    const OPERATE_START_HERE = 1000; // !!! 操作类型从 1000 开始
    const ADMIN_PANX_LOGIN = 1100; // 后台 - panx - 登录
    const ADMIN_CUSTOMER_LOGIN = 1110; // 后台 - 客户 - 登录
    const ADMIN_STORE_LOGIN = 1120; // 后台 - 店铺登录 - 登录
    const DEV_ACNT_GUEST_ADD_CART = 2010; //  App 游客把商品加入购物车
    const ERROR_START_HERE = 4000; // !!! 错误类型从 4000 开始
    const OPERATE_BOOT_EVENT = 1999; // model use ActionLogger 模型响应事件

    const FILTER_LOG_MAP = [
        self::ADMIN_PANX_LOGIN     => '后台panx登录',
        self::ADMIN_CUSTOMER_LOGIN => '后台客户登录',
        self::ADMIN_STORE_LOGIN    => '后台店铺登录',
        self::OPERATE_BOOT_EVENT   => '模型响应事件记录',
    ];

    const REMARK_MAP = [
        self::OPERATE_START_HERE => '!!! 操作类型从 1000 开始',
        self::ADMIN_PANX_LOGIN => '后台 - panx - 登录',
        self::ADMIN_CUSTOMER_LOGIN => '后台 - 客户 - 登录',
        self::ADMIN_STORE_LOGIN => '后台 - 店铺登录 - 登录',
        self::DEV_ACNT_GUEST_ADD_CART => 'App 游客把商品加入购物车',
        self::ERROR_START_HERE => '!!! 错误类型从 4000 开始',
    ];

    /**
     * @param $id
     * @return mixed|null
     */
    public static function getLogRemarkById($id)
    {
        /** @var self $type */
        $type = (new self)->find($id);

        if ($type) {
            return $type->remark;
        } else {
            return null;
        }
    }

    /**
     * 导出常量映射文本
     *
     * @example namespace App\Models\Logger
     * ; LogType::dumpConstMap();
     */
    public static function dumpConstMap()
    {
        $dump_file = storage_path('log_types.txt');
        $const_column = 'type';
        $remark_column = 'remark';

        $const_fmt = "const %s = %s; // %s " . PHP_EOL;
        $map_wrap_fmt = 'const REMARK_MAP = [' . PHP_EOL . '%s' . '];' . PHP_EOL;
        $map_fmt = "\t self::%s => '%s', " . PHP_EOL;

        $const_str = '';
        $map_str = '';
        self::all()->map(
            function (self $self) use (
                $const_column, $remark_column, $const_fmt, $map_fmt, &$const_str, &$map_str
            ) {
                $const_str .= sprintf($const_fmt, $self->{$const_column}, $self->id, $self->{$remark_column});
                $map_str .= sprintf($map_fmt, $self->{$const_column}, $self->{$remark_column});
            }
        );

        $map_str = sprintf($map_wrap_fmt, $map_str) ;

        file_put_contents($dump_file, $const_str . PHP_EOL . $map_str );

        return true;
    }
}
